import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
    Card, Button, Row, Col, Space,
    Form, Checkbox, Switch, Tabs,
    Input, message,Modal,
    Table
} from 'antd';
import {
    PlusOutlined,
    MailOutlined,
    PhoneOutlined,
    CloseOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons';
import { connect } from 'umi';
import request from '@/utils/request';
import CateComp from '@/components/CategoryComponent';
import ZoneComp from '@/components/ZoneComponent';
import { EmpSelect } from '@/components/FormItemSelect';
import DocHelper from '@/components/DocHelper';

const { TabPane } = Tabs;
const { confirm } = Modal;
const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
};

const apiURL = "/api/services/app/Customers/";
class ViewPage extends React.Component<any, any> {
    constructor(props: Readonly<{}>) {
        super(props);
        this.state = {
            loading: false,
            visible: false,
            data: {},
            dataSource: []
        }
    }
    formRef: any = React.createRef();
    componentDidMount() {
        this.fetchData();
    }
    onFinish = (values: any) => {
        const { data } = this.state;
        var Customer = values.Customer;
        Customer.id = data.id;
        request(apiURL + 'UpdateCustomer', {
            method: 'PUT',
            data: Customer
        }).then((response) => {
            if (response) {
                if (response.success) {
                    message.success('保存成功！');
                    this.fetchData();
                }
                else {
                    message.error(response.error.message);
                }
            }
        });
    }
    fetchData = () => {
        this.setState({ loading: true });
        request(apiURL + 'GetAll', {
            method: 'GET',
            params: { SkipCount: 0, MaxResultCount: 100 }
        }).then((response) => {
            if (response) {
                if (response.success) {
                    var items = response.result?.items;
                    this.setState({ dataSource: items });
                }
                else {
                    message.error(response.error.message);
                }
            }
            this.setState({ loading: false });
        });
    };
    newObj = () => {
        let value = this.formRef.current.getFieldsValue();
        request(apiURL + 'NewCustomer', {
            method: 'POST',
            data: value.Customer
        }).then((response) => {
            if (response) {
                if (response.success) {
                    if (response.result.success) {
                        message.success('新建客户成功！');
                        var data = response.result.data;
                        this.setState({ data });
                        this.formRef.current.setFieldsValue({ Customer: data });
                        this.fetchData();
                    }
                    else {
                        message.error(response.result.message);
                    }
                }
                else {
                    message.error(response.error.message);
                }
                this.setState({ loading: false });
            }
        });
    }
    delObj = () => {
        const { data } = this.state;
        let _this = this;
        confirm({
          title: '警告',
          icon: <ExclamationCircleOutlined />,
          content: '删除后将不可恢复，确定删除？',
          onOk() {            
            request(apiURL + 'Delete', {
              method: 'DELETE',
              params: { id: data.id },
            }).then((response) => {
              if (response) {
                if (response.success) {
                  _this.formRef.current.resetFields();
                  _this.fetchData();
                } else {
                  message.error(response.error.message);
                }
              }
            });
          },
        });
      };
    setData = (data: any) => {
        this.setState({ data });
        this.formRef.current.setFieldsValue({ Customer: data });
    }
    openModal = (record: any, layout: string) => {
        this.setState({ visible: true, disabled: true, record, layout });
    }
    closeModal = () => {
        this.setState({ visible: false });
    }
    handleCountryChange = (parent: string) => {
        const { optionCountry } = this.state;
        var items = optionCountry.filter((o: any) => o.categoryIndex == parent)[0];
        if (items) {
            this.setState({ optionState: items.children });
        }
    };
    handleStateChange = (parent: string) => {
        const { optionState } = this.state;
        var items = optionState.filter((o: any) => o.categoryIndex == parent)[0];
        if (items) {
            this.setState({ optionCity: items.children });
        }
    };
    resetForm = () => {
        this.setState({ data: null });
        this.formRef.current.resetFields();
    }
    render() {
        const { data } = this.state;
        const columns = [
            {
                title: '客户编号',
                dataIndex: 'custNum',
                key: 'custNum',
            },
            {
                title: '客户名称',
                dataIndex: 'customerName',
                key: 'customerName',
            },
            {
                title: '状态',
                dataIndex: 'isActive',
                key: 'isActive',
                render: (text: boolean) =>
                    <span><Switch checked={text} /></span>
            },
            {
                title: '操作',
                render: (_: any, record: any) => (
                    <Button
                        size="small"
                        type="default"
                        title="编辑"
                        onClick={() => this.setData(record)}
                    >
                        编辑
                    </Button>
                ),
            },
        ];
        return (
            <PageHeaderWrapper title={false}>
                <Form {...layout} ref={this.formRef} onFinish={this.onFinish} >

                    <Row gutter={[16, 16]}>
                        <Col xs={24} sm={24} md={24} lg={12} xl={12}>
                            <Card title={"客户管理"} extra={
                                <Space>
                                    <DocHelper page="xnzpv6" />
                                    <Button type="primary" icon={<PlusOutlined />} onClick={() => this.newObj()}>新增</Button>
                                    <Button type="default" onClick={() => this.resetForm()}>重置</Button>
                                    <Button type="primary" htmlType="submit" disabled={!data?.id}>保存</Button>
                                    <Button type="dashed" danger icon={<CloseOutlined />} onClick={() => this.delObj()} disabled={!data?.id}>删除</Button>
                                    <Button type="primary" onClick={() => this.fetchData()}>刷新</Button>                                    
                                </Space>
                            }>
                                <Tabs defaultActiveKey="1" >
                                    <TabPane tab="明细" key="1">
                                        <Form.Item
                                            label="客户代号"
                                            name={['Customer', 'custNum']}
                                            rules={[{ required: true, message: "客户代号必填" }]}>
                                            <Input style={{ width: 200 }} />
                                        </Form.Item>
                                        <Form.Item
                                            label="客户名称"
                                            name={['Customer', 'customerName']}
                                            rules={[{ required: true, message: "客户名称必填" }]}>
                                            <Input />
                                        </Form.Item>
                                        <EmpSelect showSearch width={200} name={['Customer', 'saler']} label="销售员" />
                                        <CateComp layout="Currency" width={200} cRef={this.formRef} name={['Customer', 'currency']} label="币种" />
                                        <Form.Item
                                            name={['Customer', 'contactor']}
                                            label="联系人"
                                            rules={[{ required: true, message: "请输入联系人" }]}>
                                            <Input style={{ width: 200 }} />
                                        </Form.Item>
                                        <Form.Item name={['Customer', 'email']}
                                            rules={[{ required: true, message: "请输入电子邮件" }]}
                                            label="电子邮件">
                                            <Input prefix={<MailOutlined />} style={{ width: 240 }} />
                                        </Form.Item>
                                        <Form.Item wrapperCol={{ offset: 5 }}>
                                            <Input.Group compact>
                                                <Form.Item
                                                    name={['Customer', 'isActive']}
                                                    valuePropName="checked">
                                                    <Checkbox>有效</Checkbox>
                                                </Form.Item>
                                            </Input.Group>
                                        </Form.Item>
                                    </TabPane>
                                    <TabPane tab="其它" key="2">
                                        <Form.Item name={['Customer', 'telphone']} label="联系电话">
                                            <Input prefix={<PhoneOutlined />} style={{ width: 240 }} />
                                        </Form.Item>
                                        <ZoneComp layout="Zone" width={100} label="国家/地区" name="Customer" />
                                        <Form.Item
                                            name={['Customer', 'contAddress']}
                                            label="联系地址">
                                            <Input.TextArea />
                                        </Form.Item>
                                    </TabPane>
                                </Tabs>
                            </Card>
                        </Col>
                        <Col xs={24} sm={24} md={24} lg={12} xl={12}><Card>
                            <Table rowKey="id" size="small" columns={columns}
                                loading={this.state.loading}
                                dataSource={this.state.dataSource}
                                onRow={record => {
                                    return {
                                        onDoubleClick: event => { this.setData(record) },
                                    };
                                }} />
                        </Card></Col>
                    </Row>
                </Form>
            </PageHeaderWrapper>
        )
    }
}
export default connect(({ Abp }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
}))(ViewPage);